package com.eeepay.eeepay_v2.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.eeepay.v2_library.log.LogUtils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zw on 2016/8/17 0017.
 * 各种工具方法
 */
public class AllUtils {

    private static Stack<Activity> stack;

//    /**
//     * 显示给用户看的机具号
//     *
//     * @return
//     */
//    public static String getShowDeviceName(String deviceName, String ksn) {
//        String tempName = deviceName + ksn.substring(ksn.length() - 10, ksn.length());
//        return getShowDeviceName(tempName);
//    }

//    /**
//     * 显示给用户看的机具号
//     *
//     * @return
//     */
//    public static String getShowDeviceName(String tempBlueName) {
//        String tempName = tempBlueName;
//        if (tempName.startsWith(SwipeConfig.Device_M188)) {
//            tempName = tempName.replace(SwipeConfig.Device_M188, MyApplication.getInstance().getResources().getString(R.string.app_old_name));
//        } else if (tempName.startsWith(SwipeConfig.Device_TY63250)) {
//            tempName = tempName.replace(SwipeConfig.Device_TY63250, MyApplication.getInstance().getResources().getString(R.string.app_old_name) + "T");
//        } else if (tempName.startsWith(SwipeConfig.Device_TY633)) {
//            tempName = tempName.replace(SwipeConfig.Device_TY633, MyApplication.getInstance().getResources().getString(R.string.app_old_name) + "T-NFC");
//        } else if (tempName.contains(SwipeConfig.Device_ME15)) {
//            tempName = tempName.replace(SwipeConfig.Device_ME15, MyApplication.getInstance().getResources().getString(R.string.app_old_name) + "X");
//        } else if (tempName.contains(SwipeConfig.Device_SAIFU_P27_BLUE)) {
//            tempName = tempName.replace(SwipeConfig.Device_SAIFU_P27_BLUE, MyApplication.getInstance().getResources().getString(R.string.app_old_name) + "D");
//        } else if (tempName.contains(SwipeConfig.Device_M198)) {
//            tempName = tempName.replace(SwipeConfig.Device_M198, MyApplication.getInstance().getResources().getString(R.string.app_old_name) + "B");
//        }
//        return tempName;
//    }

//    /**
//     * 动态菜单按照id从小到大排序
//     *
//     * @param info
//     * @return
//     */
//    public static List<FinanceInfo> orderByFinanceDESC(List<FinanceInfo> info) {
//        if (info == null) {
//            return info;
//        }
//        int size = info.size();
//        for (int i = 0; i < size - 1; i++) {
//            for (int j = 0; j < size - i - 1; j++) {
//                if (info.get(j).getId() > info.get(j + 1).getId()) {
//                    FinanceInfo finance = info.get(j);
//                    info.remove(j);
//                    info.add(j + 1, finance);
//                }
//            }
//        }
//
//        return info;
//    }

    public static Stack<Activity> getStack() {
        if (stack == null) {
            synchronized (AllUtils.class) {
                if (stack == null) {
                    stack = new Stack<>();
                }
            }
        }
        return stack;
    }

    public static void addActivity(Activity activity) {
        stack = getStack();
        stack.push(activity);
    }

    public static void finishActivity() {
        stack = getStack();
        while (!stack.isEmpty()) {
            stack.pop().finish();
        }

    }

//    private static CustomDialog mCustonDialog;//

//    /**
//     * 完善资料提示
//     */
//    public static void showDialog(final Context mContext) {
//
//        if (mCustonDialog == null || !mCustonDialog.isShowing()) {
//            mCustonDialog = new CustomDialog(mContext);
//            mCustonDialog.setCancelable(false);
//            mCustonDialog.setCanceledOnTouchOutside(false);
//            mCustonDialog.setMessage("您还未完善资料，请先完善资料");
//            mCustonDialog.setTitles("温馨提示");
//            mCustonDialog.setNegativeButton("取消", new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//
//                }
//            });
//            mCustonDialog.setPositiveButton("确定", new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    ScreenSwitch.switchActivity(mContext, IntoRegActivity.class, null, -1);
//                }
//            });
//        }
//        if (!mCustonDialog.isShowing()) {
//            mCustonDialog.show();
//        }
//    }


//    /**
//     * 3:审核失败；  -1服务取消了
//     * 完善资料未审核和审核失败提示  此处需要刷新商户状态
//     */
//    public static void showExamDialog(final Context mContext, final String merStatus) {
//
//        if (mCustonDialog == null || !mCustonDialog.isShowing()) {
//            mCustonDialog = new CustomDialog(mContext);
//            mCustonDialog.setCancelable(true);
//            mCustonDialog.setCanceledOnTouchOutside(true);
//            if ("3".equals(merStatus)) {
//                mCustonDialog.setMessage("进件失败，请重新修改资料!");
//                mCustonDialog.setPositiveButton("确定", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if ("3".equals(merStatus)) {
//                            ScreenSwitch.switchActivity(mContext, CollectionServeActivity.class, null, -1);
//                            return;
//                        }
//                    }
//                });
//                mCustonDialog.setNegativeButton("取消", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//
//                    }
//                });
//            } else if ("-1".equals(merStatus)) {
//                mCustonDialog.setMessage("商户没有收款服务，请申请");
//                mCustonDialog.setOneButton("确定", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        ScreenSwitch.switchActivity(mContext, CollectionServeActivity.class, null, -1);
//                        mCustonDialog.dismiss();
//                    }
//                });
//            } else {
//                mCustonDialog.setMessage("您的进件资料还未审核通过，请等待");
//                mCustonDialog.setOneButton("确定", new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        Map<String, String> params = ApiUtil.getParams();
//                        params.put("merchantNo", UserData.getUserDataInSP().getMerchantNo());
//                        OkHttpClientManager.postAsyn(ApiUtil.get_mer_status_url, params
//                                , new OkHttpClientManager.ResultCallback<String>() {
//                                    @Override
//                                    public void onError(Request request, Exception e) {
//                                        mCustonDialog.dismiss();
//                                    }
//
//                                    @Override
//                                    public void onResponse(String response) {
//                                        LogUtils.d("getMerStatusApi ：response = " + response);
//                                        MerStatusModel model = new Gson().fromJson(response, MerStatusModel.class);
//                                        if (!model.getHeader().getSucceed()) {
//                                            Toast.makeText(mContext, model.getHeader().getErrMsg(), Toast.LENGTH_SHORT).show();
//                                            return;
//                                        }
//                                        UserData data = UserData.getUserDataInSP();
//                                        data.setMerStatus(model.getBody().getStatus());
//                                        data.saveUserInfo();
//                                        mCustonDialog.dismiss();
//                                    }
//                                });
//                    }
//                });
//            }
//
//        }
//        mCustonDialog.show();
//    }
//
//    private static HappyDialog dialog;
//
//    /**
//     * 欢乐送提示
//     *
//     * @param mContext
//     */
//    public static void showHappySendDialog(final Context mContext, final String froMoney,String content) {
//        if (dialog == null || !dialog.isShowing()) {
//            dialog = new HappyDialog(mContext);
//            dialog.show();
//            dialog.setCancelable(false);
//            dialog.setContent(content);
//            dialog.setClicklistener(new HappyDialog.ClickListenerInterface() {
//                @Override
//                public void doConfirm() {
//                    Bundle bundle = new Bundle();
//                    bundle.putString(Constans.INTENT_FLAG, Constans.CONNECT_HAPPY_SEND);
//                    bundle.putString(Constans.FROZEN_MONEY,froMoney);
//                    ScreenSwitch.switchActivity(mContext, ConnectDeviceActivity.class, bundle, -1);
////                    ScreenSwitch.switchActivity(mContext, HappyStarActivity.class, null, -1);
//                    dialog.dismiss();
//                }
//
//                @Override
//                public void doAgree() {
//                    Bundle bundle = new Bundle();
//                    bundle.putString("url", ApiUtil.happy_send_agreement);
//                    ScreenSwitch.switchActivity(mContext, WebViewActivity.class, bundle, -1);
//                }
//
//                @Override
//                public void doCancel() {
//                    dialog.dismiss();
//                }
//            });
//        }
//    }

    /**
     * 到账状态
     *
     * @param method
     * @return
     */
    public static String payMethod(String settleType, String method) {
        switch (settleType) {
            case "1":
                if ("0".equals(method)) {
                    return "实时出款";
                } else if ("1".equals(method)) {
                    return "普通出款";
                } else {
                    return "其他出款";
                }
            case "2":
                return "手工提现";
            case "3":
            case "4":
                return "T1结算";
        }
        return null;
    }

    /**
     * 结算状态
     *
     * @param status
     * @return
     */
    public static String settleStatus(String status) {
        //结算状态1：已结算  0或空：未结算   2.结算中   3.结算失败
        if ("1".equals(status)) {
            return "已结算";
        } else if ("0".equals(status) || TextUtils.isEmpty(status)) {
            return "未结算";
        } else if ("2".equals(status)) {
            return "结算中";
        } else if ("3".equals(status)) {
            return "结算失败";
        }
        return "其他";
    }

    /**
     * @param settleType
     * @param method
     * @param settleMethod
     * @return 如果是1的话，就按目前的刷卡即时结算 来拼； 如果是2，显示成手工提现；如果是3或4，显示成 T1结算
     */
    public static String collectionMethod(String settleType, String method, String settleMethod) {
        switch (settleType) {
            case "1":
                if ("0".equals(settleMethod)) {
                    return collectionPayMethod(method) + "即时收款";
                } else if ("1".equals(settleMethod)) {
                    return collectionPayMethod(method) + "普通收款";
                } else {
                    return collectionPayMethod(method) + "收款";
                }
            case "2":
                return "手工提现";
            case "3":
            case "4":
                return "T1结算";
        }
        return null;
    }

    /**
     * @param method       收款方式；pos，支付宝，微信，快捷
     * @param settleMethod 出款方式：t0;t1
     * @return
     */
    public static String collectionMethod(String method, String settleMethod) {

        if ("0".equals(settleMethod)) {
            return collectionPayMethod(method) + "即时收款";
        } else if ("1".equals(settleMethod)) {
            return collectionPayMethod(method) + "普通收款";
        } else {
            return collectionPayMethod(method) + "收款";
        }

    }

    private static String collectionPayMethod(String paymethod) {
        if ("1".equals(paymethod)) {
            return "刷卡";
        } else if ("2".equals(paymethod)) {
            return "支付宝";
        } else if ("3".equals(paymethod)) {
            return "微信";
        } else if ("4".equals(paymethod)) {
            return "快捷";
        } else {
            return "";
        }


    }

    /**
     * 收款状态
     *
     * @param status
     * @return 成功SUCCESS, 失败FAILED, 初始化INIT, 已冲正REVERSED, 已撤销REVOKED,* 已结算SETTLE, 超额OVERLIMIT,已退款REFUND 已完成, COMPLETE 关闭,CLOSED;
     */
    public static String collectionStatus(String status) {
        if ("SUCCESS".equals(status)) {
            return "交易成功";
        } else if ("FAILED".equals(status)) {
            return "交易失败";
        } else if ("INIT".equals(status)) {
            return "初始化";
        } else if ("REVERSED".equals(status)) {
            return "已冲正";
        } else if ("REVOKED".equals(status)) {
            return "已撤销";
        } else if ("SETTLE".equals(status)) {
            return "已结算";
        } else if ("OVERLIMIT".equals(status)) {
            return "超额";
        } else if ("REFUND".equals(status)) {
            return "已退款";
        } else if ("COMPLETE".equals(status)) {
            return "已完成";
        } else if ("CLOSED".equals(status)) {
            return "关闭";
        } else {
            return "其他";
        }
    }

    /**
     * 判断SD卡是否存在
     *
     * @return
     */
    public static boolean sdCardIsExit() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取SD卡路径
     *
     * @return /sdcard/
     */
    public static String getSDCardPath() {
        if (sdCardIsExit()) {
            return Environment.getExternalStorageDirectory().toString() + "/";
        }
        return null;
    }


    /**
     * 创建文件夹
     *
     * @param dirPath
     */
    public static String creatDir2SDCard(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {// 判断文件是否存在
            file.mkdirs();
        }
        return dirPath;
    }


    /**
     * 检验字符串是否为空；包括：null，""," "。
     *
     * @param str 检验字符串
     * @return boolean true为空字符串；false为非空字符串。
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 创建文件
     * <p>
     * 如果是/sdcard/download/123.doc则只需传入filePath=download/123.doc
     *
     * @param filePath 文件路径
     * @return 创建文件的路径
     * @throws IOException
     */
    public static String creatFile2SDCard(String filePath) throws IOException {
        // 无论传入什么值 都是从根目录开始 即/sdcard/+filePath
        // 创建文件路径包含的文件夹
        String filedir = creatDir2SDCard(getFileDir(filePath));
        String fileFinalPath = filedir + getFileName(filePath);
        File file = new File(fileFinalPath);
        if (!file.exists()) {
            file.createNewFile();
        }
        return fileFinalPath;
    }

    /**
     * 获取文件目录路径
     *
     * @param filePath
     * @return
     */
    private static String getFileDir(String filePath) {
        if (filePath.startsWith(getSDCardPath())) {
            return filePath.replace(getFileName(filePath), "");
        }
        return getSDCardPath() + filePath.replace(getFileName(filePath), "");
    }

    /**
     * 获取文件名
     *
     * @param filePath
     * @return
     */
    private static String getFileName(String filePath) {
        int index = 0;
        String tempName = "";
        if ((index = filePath.lastIndexOf("/")) != -1) {
            // 如果有后缀名才
            tempName = filePath.substring(index + 1);
        }
        return tempName.contains(".") ? tempName : "";
    }

    /**
     * 用于动态时间格式化 将日期时间格式为 今天 昨天 前天
     *
     * @param time
     * @return
     */
    public static String getFormatTime(String time) {
        String reTime = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.roll(Calendar.DAY_OF_YEAR, -2);
        String beforeTwo = df.format(calendar.getTime());

        calendar.roll(Calendar.DAY_OF_YEAR, 1);

        String yesterDay = df.format(calendar.getTime());
        calendar = Calendar.getInstance();
        String toDay = df.format(calendar.getTime());

        // 取年份
        calendar = Calendar.getInstance();
        String strYear = String.valueOf(calendar.get(Calendar.YEAR));// 获取当前年时间并转为字符串型
        if (time != null && time.length() > 16) {
            reTime = time.substring(0, 16);
            String pubTime = time.substring(0, 10);// 取天数
            String yearTime = time.substring(0, 4);// 取年份

            if (toDay.equals(pubTime)) {
                reTime = "今天  " + time.substring(11, 16);
            } else if (yesterDay.equals(pubTime)) {
                reTime = "昨天  " + time.substring(11, 16);
            } else if (beforeTwo.equals(pubTime)) {
                reTime = "前天  " + time.substring(11, 16);
            } else if (strYear.equals(yearTime)) {
                reTime = time.substring(0, 11);// 前天以上的只显示天
            }
        }
        return reTime;
    }

//    /**
//     * @param temp 参数加密
//     */
//    public static String setReqParam(String temp, Map<String, String> reqaram) {
//        ArrayList<String> mReqaram = new ArrayList<>();
//        String temps = temp.substring(0, temp.length() - 1);// 拼串
//        String md5 = Md5.encode(temps);// md5的时候把temp中的最后一个&符号去掉
//        String allData = temp + "sign=" + md5;
//        // int allDataSize = allData.getBytes(Charset.forName("utf-8")).length;
//        int allDataSize = allData.length();
//        int forSize = allDataSize / 117;
//        LogUtils.d("forSize=" + forSize);
//        LogUtils.d("allDataSize % 117=" + allDataSize % 117);
//        if (allDataSize % 117 > 0) {
//            forSize = allDataSize / 117 + 1;
//        }
//        LogUtils.d("forSize2=" + forSize);
//        String[] allDatas = new String[forSize];
//        String[] md5base64Datas = new String[forSize];
//        String tempResult = "";
//        for (int i = 0; i < forSize; i++) {// 把所有的字符分割117,因为rsa加密字符串有限，先分隔，在rsa再base64
//            if (i == forSize - 1) {
//                allDatas[i] = allData.substring(i * 117, allDataSize);
//            } else {
//                allDatas[i] = allData.substring(i * 117, (i + 1) *
//
//                        117);
//
//            }
//            try {
//                md5base64Datas[i] = Base64.encode(EncRSA.EncPass(allDatas[i]));// rsa
//            } catch (Exception e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//            if (i == 0) {
//                tempResult = md5base64Datas[0];
//            } else {
//                tempResult += "&data=" + md5base64Datas[i];
//            }
//            mReqaram.add(md5base64Datas[i]);
//        }
//
//        LogUtils.d("tempResult=" + tempResult);
//        // mReqaram.put("data", tempResult);
//
//        return tempResult;
//    }
//
//    /**
//     * 判断是否有输入键盘的设备
//     *
//     * @return
//     */
//    public static boolean isHavePwdKey(String diviDevice) {
//        if (SwipeConfig.Device_TY.equals(diviDevice)
//                || SwipeConfig.Device_ME30.equals(diviDevice)
//                || SwipeConfig.Device_M368.equals(diviDevice)
//                || SwipeConfig.Device_SAIFU_P8.equals(diviDevice)) {
//            return true;
//        }
//
//        return false;
//    }

    public static boolean isAppRunning(Context context) {
        String packageName = "com.eeepay.eeepay_v2"; //context.getPackageName();
        String topActivityClassName = getTopActivityName(context);
        if (packageName != null && topActivityClassName != null && topActivityClassName.startsWith(packageName)) {
            return true;
        } else {
            return false;
        }
    }

    public static String getTopActivityName(Context context) {
        String topActivityClassName = null;
        ActivityManager activityManager =
                (ActivityManager) (context.getSystemService(android.content.Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(1);
        if (runningTaskInfos != null) {
            ComponentName f = runningTaskInfos.get(0).topActivity;
            topActivityClassName = f.getClassName();
        }
        return topActivityClassName;
    }

    /**
     * 判断当前应用程序处于前台还是后台
     * 需要添加权限: <uses-permission android:name="android.permission.GET_TASKS" />
     */
    public static boolean isApplicationBackground(final Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                LogUtils.d("isBackground: " + true);
                return true;
            }
        }
        LogUtils.d("isBackground: " + false);
        return false;
    }

    /**
     * 获取设备id（IMEI）
     *
     * @param context
     * @return
     */
    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    public static String getDeviceIMEI(Context context) {
        String deviceId;
        TelephonyManager telephony = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = telephony.getDeviceId();
        if (deviceId == null) {
            deviceId = Settings.Secure.getString(context.getContentResolver(),
                    Settings.Secure.ANDROID_ID);
        }
        LogUtils.d("当前设备IMEI码: " + deviceId);
        return deviceId != null ? deviceId : "Unknown";
    }

    /**
     * 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
     *
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) throws Exception {
        if (version1 == null || version2 == null) {
            throw new Exception("compareVersion error:illegal params.");
        }
        String[] versionArray1 = version1.split("\\.");//注意此处为正则匹配，不能用"."；
        String[] versionArray2 = version2.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
            ++idx;
        }
        //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }

    /**
     * 判断字符串是否全部为中文字符组成
     *
     * @param str 检测的文字
     * @return true：为中文字符串，false:含有非中文字符
     */
    public static boolean isChineseStr(String str) {
        Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
        char c[] = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            Matcher matcher = pattern.matcher(String.valueOf(c[i]));
            if (!matcher.matches()) {
                return false;
            }
        }
        return true;
    }

    /**
     * java中判断字段真实长度的实例(中文2个字符,英文1个字符)
     * @param value
     * @return
     */
    public static int String_length(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength;
    }

}
